package com.algorithm.binary;

import java.util.Arrays;

public class Solution1011 {

    public int shipWithinDays(int[] weights, int D) {
        //获取单次运输的最大重量 ， 单次不能低于 此重量。
        int l = Arrays.stream(weights).max().getAsInt();
        //所有的重量和  ， 为 单次 运输的上限。
        int r = Arrays.stream(weights).sum();

        while(l < r){

            int mid = l + (r - l) / 2;
            if(days(weights,mid) <= D) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }

    private int days(int[] weights, int k){
        int cur = 0, res = 0;
        for(int weight: weights) {
            if(cur + weight <= k) {
                cur += weight;
            } else{
                res ++;
                cur = weight;
            }
        }
        res ++;
        return res;
    }
}